package com.example.backend.controller;

import com.example.backend.domain.entity.User;
import com.example.backend.domain.enums.Role;
import com.example.backend.domain.enums.UserStatus;
import com.example.backend.dto.*;
import com.example.backend.mapper.SimpleMappers;
import com.example.backend.constants.RoleConstants;
import com.example.backend.security.RequirePermission;
import com.example.backend.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.List;

/**
 * 用户管理控制器
 * 提供完整的用户CRUD操作和权限管理
 */
@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户信息的增删改查和权限管理")
@SecurityRequirement(name = "Bearer Authentication")
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    // 用户CRUD操作

    @GetMapping
    @Operation(summary = "获取用户列表", description = "分页获取用户列表，支持多条件过滤与排序")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<PageResponse<UserDto>>> list(
            UserFilter filter,
            Pageable pageable) {
        try {
            Page<UserDto> page = userService.findAll(filter, pageable).map(SimpleMappers::toUserDto);
            return ResponseEntity.ok(ApiResponse.success(PageResponse.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取用户列表失败: " + e.getMessage()));
        }
    }

    @PostMapping
    @Operation(summary = "创建新用户", description = "创建新的用户账号")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<UserDto>> create(@Valid @RequestBody CreateUserRequest request) {
        try {
            User user = userService.createUser(request);
            return ResponseEntity.ok(ApiResponse.success("用户创建成功", SimpleMappers.toUserDto(user)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("创建用户失败: " + e.getMessage()));
        }
    }

    @GetMapping("/{userId}")
    @Operation(summary = "获取用户详情", description = "根据用户ID获取详细信息")
    @RequirePermission(roles = {RoleConstants.ADMIN, RoleConstants.AGENT})
    public ResponseEntity<ApiResponse<UserDto>> getById(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        try {
            User user = userService.findById(userId)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            return ResponseEntity.ok(ApiResponse.success(SimpleMappers.toUserDto(user)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取用户失败: " + e.getMessage()));
        }
    }

    @PutMapping("/{userId}")
    @Operation(summary = "更新用户信息", description = "更新用户的基本信息")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<UserDto>> update(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Valid @RequestBody UpdateUserRequest request) {
        try {
            User user = userService.updateUser(userId, request);
            return ResponseEntity.ok(ApiResponse.success("用户信息更新成功", SimpleMappers.toUserDto(user)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("更新用户失败: " + e.getMessage()));
        }
    }

    @DeleteMapping("/{userId}")
    @Operation(summary = "删除用户", description = "删除指定的用户账号")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<String>> delete(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        try {
            userService.deleteUser(userId);
            return ResponseEntity.ok(ApiResponse.success("用户删除成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("删除用户失败: " + e.getMessage()));
        }
    }

    // 用户状态管理

    @PutMapping("/{userId}/status")
    @Operation(summary = "更新用户状态", description = "更新用户的账户状态")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<UserDto>> updateStatus(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @RequestParam UserStatus status) {
        try {
            User user = userService.updateUserStatus(userId, status);
            return ResponseEntity.ok(ApiResponse.success("用户状态更新成功", SimpleMappers.toUserDto(user)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("更新用户状态失败: " + e.getMessage()));
        }
    }

    @PutMapping("/{userId}/password")
    @Operation(summary = "重置用户密码", description = "重置指定用户的密码")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<String>> resetPassword(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @RequestParam String newPassword) {
        try {
            userService.resetUserPassword(userId, newPassword);
            return ResponseEntity.ok(ApiResponse.success("密码重置成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("密码重置失败: " + e.getMessage()));
        }
    }

    // 权限管理

    @PutMapping("/{userId}/permissions")
    @Operation(summary = "更新用户权限", description = "更新指定用户的权限列表")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<String>> updatePermissions(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @RequestBody UpdateUserPermissionsRequest request) {
        try {
            // 这里可以实现更复杂的权限管理逻辑
            // 目前权限是基于角色的，所以这里可以更新用户角色
            return ResponseEntity.ok(ApiResponse.success("权限更新成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("权限更新失败: " + e.getMessage()));
        }
    }

    // 搜索和筛选

    @GetMapping("/search")
    @Operation(summary = "搜索用户", description = "根据关键词搜索用户")
    @RequirePermission(roles = {RoleConstants.ADMIN, RoleConstants.AGENT})
    public ResponseEntity<ApiResponse<PageResponse<UserDto>>> search(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Role role,
            @RequestParam(required = false) UserStatus status,
            @RequestParam(required = false) String department,
            Pageable pageable) {
        try {
            Page<UserDto> page = userService.searchUsers(keyword, role, status, department, pageable)
                    .map(SimpleMappers::toUserDto);
            return ResponseEntity.ok(ApiResponse.success(PageResponse.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("搜索用户失败: " + e.getMessage()));
        }
    }

    @GetMapping("/role/{role}")
    @Operation(summary = "根据角色获取用户", description = "根据用户角色获取用户列表")
    @RequirePermission(roles = {RoleConstants.CUSTOMER, RoleConstants.AGENT, RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<PageResponse<UserDto>>> getByRole(
            @Parameter(description = "用户角色") @PathVariable Role role,
            Pageable pageable) {
        try {
            Page<UserDto> page = userService.findByRole(role, pageable).map(SimpleMappers::toUserDto);
            return ResponseEntity.ok(ApiResponse.success(PageResponse.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取用户列表失败: " + e.getMessage()));
        }
    }

    @GetMapping("/status/{status}")
    @Operation(summary = "根据状态获取用户", description = "根据用户状态获取用户列表")
    @RequirePermission(roles = {RoleConstants.ADMIN, RoleConstants.AGENT})
    public ResponseEntity<ApiResponse<PageResponse<UserDto>>> getByStatus(
            @Parameter(description = "用户状态") @PathVariable UserStatus status,
            Pageable pageable) {
        try {
            Page<UserDto> page = userService.findByStatus(status, pageable).map(SimpleMappers::toUserDto);
            return ResponseEntity.ok(ApiResponse.success(PageResponse.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取用户列表失败: " + e.getMessage()));
        }
    }

    @GetMapping("/department/{department}")
    @Operation(summary = "根据部门获取用户", description = "根据部门获取用户列表")
    @RequirePermission(roles = {RoleConstants.ADMIN, RoleConstants.AGENT})
    public ResponseEntity<ApiResponse<PageResponse<UserDto>>> getByDepartment(
            @Parameter(description = "部门名称") @PathVariable String department,
            Pageable pageable) {
        try {
            Page<UserDto> page = userService.findByDepartment(department, pageable).map(SimpleMappers::toUserDto);
            return ResponseEntity.ok(ApiResponse.success(PageResponse.of(page)));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取用户列表失败: " + e.getMessage()));
        }
    }

    // 统计和分析

    @GetMapping("/statistics")
    @Operation(summary = "获取用户统计信息", description = "获取用户角色分布、部门统计等信息")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<UserService.UserStatistics>> getStatistics() {
        try {
            UserService.UserStatistics statistics = userService.getUserStatistics();
            return ResponseEntity.ok(ApiResponse.success(statistics));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取统计信息失败: " + e.getMessage()));
        }
    }

    @GetMapping("/trend")
    @Operation(summary = "获取用户趋势分析", description = "获取指定时间范围内的用户注册趋势")
    @RequirePermission(roles = {RoleConstants.ADMIN})
    public ResponseEntity<ApiResponse<List<Object[]>>> getTrendAnalysis(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant endDate) {
        try {
            List<Object[]> trendData = userService.getUserTrendAnalysis(startDate, endDate);
            return ResponseEntity.ok(ApiResponse.success(trendData));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取趋势分析失败: " + e.getMessage()));
        }
    }

    @GetMapping("/active")
    @Operation(summary = "获取活跃用户", description = "获取指定时间内的活跃用户列表")
    @RequirePermission(roles = {RoleConstants.ADMIN, RoleConstants.AGENT})
    public ResponseEntity<ApiResponse<List<UserDto>>> getActiveUsers(
            @RequestParam(defaultValue = "7") Integer days) {
        try {
            Instant since = Instant.now().minusSeconds(days * 24 * 3600);
            List<UserDto> users = userService.getActiveUsers(since)
                    .stream()
                    .map(SimpleMappers::toUserDto)
                    .toList();
            return ResponseEntity.ok(ApiResponse.success(users));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取活跃用户失败: " + e.getMessage()));
        }
    }

    @GetMapping("/latest")
    @Operation(summary = "获取最新用户", description = "获取最新注册的用户列表")
    @RequirePermission(roles = {RoleConstants.ADMIN, RoleConstants.AGENT})
    public ResponseEntity<ApiResponse<List<UserDto>>> getLatestUsers() {
        try {
            List<UserDto> users = userService.getLatestUsers()
                    .stream()
                    .map(SimpleMappers::toUserDto)
                    .toList();
            return ResponseEntity.ok(ApiResponse.success(users));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取最新用户失败: " + e.getMessage()));
        }
    }
}
